function $$(obj){
	TX.Test.alertAll(obj)
}
function CardMgnt(){}

CardMgnt.PERSONALVIEW = "personal_view"
CardMgnt.COMPANYUSER = "company_view"
CardMgnt.DRIVERUSER = "driver_view"
CardMgnt.ANONYMOUSUSER = "anonymous"

CardMgnt.PERSONALALL = "personal_all"
CardMgnt.COMPANYALL = "company_all"

//卡运营管理模块js方法

CardMgnt.getFee = function(feeType,cardTypeId){
	var localCache = Common.getLocalCache()
	if (!feeType) return;
	var key = "cardfee."+feeType;
	if (cardTypeId)
		key += "_" + cardTypeId;
		
	var fee = localCache[key]
	if (!fee){	
		fee = DWR.syncCall("feeService.getFee",feeType,cardTypeId)
		localCache[key] = fee;
	}
	return fee;
}
CardMgnt.getCardAndPin = function(){
	var res = {}
	getCard();
	res.asn = getAsn();
	res.cardPin = CardMgnt.inputCardPin(); 
	verifyPin(res.cardPin);
	return res;
}
CardMgnt.findCardNeedPin = function(formName,checkHandle){
	return CardMgnt.findCard(formName,checkHandle,true)
}
CardMgnt.findCard = function(formName,checkHandle,needPin){
	var service = "mgntQueryService.getCardInfo";
	return CardMgnt.onFindCard(formName,service,checkHandle,needPin);
}
CardMgnt.onFindCard = function(form,service,checkHandle,needPin){
	if(typeof form == "string")form = $(form)
	if (!form) {throw new Error("无法找到form")};
	
	form.reset();
	var cardPin;
	getCard();
	if (needPin){
		cardPin = CardMgnt.inputCardPin();
		verifyPin(cardPin);
	}
	var asn = getAsn();
	var data = DWR.syncCall(service,asn);
	data.cardPin = cardPin;
	if (typeof checkHandle == "function") checkHandle(data.card,data.cardType,data)
	Common.setValues(form,CardMgnt.convertCardObject(data));
	return data
}
//选择客户帐户
CardMgnt.selCardUser = function(handle,options){
	var title = "查询单位帐户";
	if (options&&options.cardUserType == CardUserType.NAME)
		title = "查询个人帐户";
			
	var url = spellUrl("/card/sel_orguser.html",options)
	openDialogFrame(url,title,400,500,handle)	
}
//选择部门
CardMgnt.selDept = function(handle,options){
	var url = spellUrl("/card/sel_dept.html",options)		
	openDialogFrame(url,'选择部门',300,400,handle);
}
CardMgnt.selFuel = function(handle,options){
	var url = spellUrl("/card/sel_fuel.html",options)		
	openDialogFrame(url,'选择油品',500,600,handle);
}

//选择车辆型号
CardMgnt.selCarModel = function(handle,options){
	var url = spellUrl("/basic/sel_carmodel_mgnt.html",options)		
	openDialogFrame(url,'选择车辆型号',320,500,handle);
}
//设置限站信息
CardMgnt.editStationLimit = function(handle,options){
	var url = spellUrl("/card/edit_station_limit.html",options)		
	openDialogFrame(url,'设置限站信息',500,600,handle);
}

CardMgnt.usePinApp = function(asn,usePin,oldPin){
	if (!CardMgnt.checkCardAsn(asn)) return;
	return CardMgnt._usePinApp(asn,usePin,oldPin);
}
CardMgnt._usePinApp = function(asn,usePin,oldPin){
	var data = {};
	var pin = null;
	if (usePin){
		var repeat;
		pin = CardMgnt.inputCardPin("请持卡人输入新的密码",true);
		if(!pin)
			throw new Error("密码输入被取消！");
			
		repeat = CardMgnt.inputCardPin("请持卡人再次输入新的密码",true);
		if(!pin)
			throw new Error("密码输入被取消！");
		
		if (pin != repeat){
			var err = new Error("两次输入的密码不一致！")
			err.type = "repeat";
			throw err;
		}
		data = DWR.syncCall("cardMgntService.usePinApp",asn,true);
		evalCardReturn(cardCom.changePIN(hCard,Constants.DEFPIN,pin));  //写卡信息
		startUsePin(pin);
	}else{
		if (oldPin)
			pin = oldPin;
		else{
			pin = CardMgnt.inputCardPin();
			if(!pin)
				throw new Error("密码输入被取消！");
		}
		
		data = DWR.syncCall("cardMgntService.usePinApp",asn,false);
		evalCardReturn(cardCom.changePIN(hCard,pin,Constants.DEFPIN));
		stopUsePin(Constants.DEFPIN);
	}
	data.pin = pin;
	return data;
}

//同步卡数据
CardMgnt.syncCardData = function(asn,pin){
	if (!pin)
		pin = Constants.DEFPIN
	CardMgnt.throwCardAsnErr(asn);
	
	var result = CardMgnt.syncCardInfo(asn,pin);					//写卡个人信息
	CardMgnt.editExpiredDate(asn,result.expiredTime,pin);			//写有效期
	CardMgnt.syncOilInfo(asn,pin);									//写限制信息
}
//写个人信息
CardMgnt.syncCardInfo = function(asn,pin){
	var rand = getRandom();											//获取随机数
	var result = DWR.syncCall("cardMgntService.getCardInfoForUpdate",asn,rand);
	
	var datamac = result.datamac;
	var carddata = datamac.substr(0,150).toUpperCase(); 	//前140位是转换成16进制的字符串
	var mac = datamac.substr(150,8).toUpperCase();			//后8位是MAC
	if (!pin)
		pin = Constants.DEFPIN
	re = evalCardReturn(cardCom.personal(hCard,pin,carddata,mac));
	
	return result
}
//写限制信息
CardMgnt.syncOilInfo = function(asn,pin){
	var rand = getRandom();												//获取随机数
	var result = DWR.syncCall("cardMgntService.getOilInfoForUpdate",asn,rand);
	updateAppInfo(pin,result.data,result.macData);
}
//写有效期
CardMgnt.editExpiredDate = function(asn,valid,pin){  //修改应用有效日期
	if(!valid) {showError("请填写日期");return;}
	updateValid(valid,pin)
}

CardMgnt.checkMasterCard = function(companyUserId,errMsg){
	getCard();
	var asn = getAsn();
	var data = DWR.syncCall("mgntQueryService.findOkCompanyUser",asn);
	var orgUser = data.cardUser;
	if (companyUserId != orgUser.id) throw new Error(errMsg);
}

CardMgnt.getContractTypes = function(){
	return DWR.syncCall("mgntQueryService.findContractTypes");
}

CardMgnt.cardUser = {
	formName : "CardUserViewForm"
}

/**
 * 显示帐户信息
 */
CardMgnt.cardUser.show = function(divId,id,viewType,options){
	var result;
	if (id){
		result = DWR.syncCall("customerService.getCardUserInfo",id);
	}
	
	CardMgnt.cardUser.showData(divId,result,viewType,options);
}


CardMgnt.cardUser.showData = function(divId,data,viewType,options){
	if (!options) options = {}
	
	var cardUser = data?CardMgnt.parseCardUser(data):{currentLevel:Constants.CUSTOMERLEVEL_NORMAL,usePin:false,isMerLimit:false,isOilLimit:false}
	
	var formName = CardMgnt.cardUser.formName;
	var url = "/card/cardquery_user_div.html";
	
	if (viewType == CardMgnt.PERSONALVIEW){						//个人档案帐户信息浏览
		url = "/card/personal_user_div.html";
	}else if (viewType == CardMgnt.COMPANYUSER){				//单位档案帐户信息浏览
		url = "/card/company_user_div.html";
	}else if (viewType == CardMgnt.PERSONALALL){				//最全的个人帐户信息
		url = "/card/personal_user_all_div.html";
	}else if (viewType == CardMgnt.COMPANYALL){					//最全的单位帐户信息
		url = "/card/company_user_all_div.html";
	}
	Rpc.loadPage(divId,url);
	var form = $(formName)
	Common.initDict(form.idnoType,"idno_type","请选择");
	if (form.status && form.status.tagName == "SELECT")
		Common.initDict(form.status,"carduser_status","请选择");
	Common.initDict(form.oilNo,"oil_number","请选择");
	var invoiceTypeList = []
	invoiceTypeList.push(InvoiceType.CONSUME)
	invoiceTypeList.push(InvoiceType.DEPOSIT)
	invoiceTypeList.push(InvoiceType.VAT)
	Common.initDict(form.invoiceType,Common.getSubsetItems(InvoiceType.CATEGORY,invoiceTypeList),"请选择");
	Common.initDict(form.currentLevel,"customer_level","请选择");
	Common.initMultiSelect("merchandiseLimitTD","可购商品",formName,"merLimitSel","/card/sel_goods_category.html",460,15);
	Common.initMultiSelect("oilLimitTD","可购油品",formName,"oilLimitSel","/card/sel_goodsgroup.html",460,8);
	Common.initMultiSelect("stationLimitTD","定点油站",formName,"stationLimitSel","/card/sel_station_limit.html",500,10);
	
	if(options.contract){
		Common.initDict(form.contractType,CardMgnt.getContractTypes(),"－－");
		form.contractType.disabled = false;
		form.contractType.className = "";
	}else{
		var contractTypes = new Array()
		if (cardUser.contractType)
			contractTypes[0] = {code:cardUser.contractType,text:cardUser.contractType}
		Common.initDict(form.contractType,contractTypes,"－－");
	}
	//设置单位下司机的卡片类型
	var cardTypeObj = $("cardType_tempelt_ccu");
	if (cardTypeObj){
		if (cardUser.id)
			cardTypeObj.style.display = "none";
		else
			cardTypeObj.onclick = function(){
				CardStore.selCardType(function(ct){
						form.cardTypeName.value = ct[1];
						form.cardType.value = ct[0];
					},{defBaseCardType:BaseCardType.COMPANY});
				return false;
			}
	}
	//设置车辆型号
	var carModelObj = $("carModel_tempelt_ccu");
	if (carModelObj)
		carModelObj.onclick = function(){
			CardMgnt.selCarModel(function(carModel){
					form.carModelName.value = carModel.name;
					form.carModel.value = carModel.id;
				});
			return false;
		}

	var area = Common.cOrg();
	if (cardUser.id){
		if (form.invoiceType){
			form.invoiceType.disabled = true;
			form.invoiceType.className = "disabled";
		}
		if (data.buildFileStation)
			area = data.buildFileStation;
	}
	CardMgnt.cardUser.setValues(formName,cardUser);
	if (options.isView)
		CardMgnt.showViewForm(formName);
}

CardMgnt.cardUser.get = function(){
	return CardMgnt.getCardUser(CardMgnt.cardUser.formName);
}
CardMgnt.cardUser.setValues = function(formName,cardUser){
	var form = $(formName);
	CardMgnt.setLimitCtrl(form,cardUser);
	cardUser.timeLimit = cardUser.timeLimit?cardUser.timeLimit:'';
	cardUser.quantityLimit = cardUser.quantityLimit?cardUser.quantityLimit:'';
	cardUser.amountLimit = cardUser.amountLimit?Format.fenToYuan(cardUser.amountLimit):'';
	cardUser.quantityNumber = cardUser.quantityNumber?cardUser.quantityNumber:'';
	cardUser.frequency = cardUser.frequency?cardUser.frequency:'';
	Common.setValues(formName,cardUser);
//	CardMgnt.setStationLimitCtrl(form.stationLimitSel,cardUser.stationLimit);
//	CardMgnt.setMerLimitCtrl(form.merLimitSel,cardUser.merchandiseLimit);
//	CardMgnt.setOilLimitCtrl(form.oilLimitSel,cardUser.oilLimit);
	CardMgnt.checkLimitCtrl(form.merLimitSel,cardUser.isMerLimit);
	CardMgnt.checkLimitCtrl(form.oilLimitSel,cardUser.isOilLimit);
}
CardMgnt.cardUser.save = function(){
	var cardUser = CardMgnt.cardUser.get();
	var service = "customerService.savePersonalCardUser";
	if (cardUser.type == CardUserType.COMPANY)
		service = "customerService.saveCompanyCardUser";
	DWR.call(service,cardUser,function(res){
		showInformation("客户帐户保存成功！");
		if (CardMgnt.cardUser.saveHandle) CardMgnt.cardUser.saveHandle(res)
	},{blockScreen:true});
}
/**
 * 取得cardUser
 * @param formName
 */
CardMgnt.getCardUser = function(formName){
	var cardUser = Common.getValues(formName);
	var form = $(formName);
	cardUser.stationLimit = CardMgnt.formatStationLimit(form.stationLimitSel);
	cardUser.merchandiseLimit = CardMgnt.formatMerchandiseLimit(form.merLimitSel,cardUser.isMerLimit);
	cardUser.oilLimit = CardMgnt.formatOilLimit(form.oilLimitSel,cardUser.isOilLimit);
	cardUser.amountLimit = cardUser.amountLimit?Format.yuanToFen(cardUser.amountLimit):0
	return cardUser;
}
CardMgnt.drivers = {
	qt : null,
	cols : {					//属性对应的列
		id : 0,
		status : 9
	}
}
/**
 * 单位司机列表
 * 
	 options = {
	 	operatRender : function(){},	//表示操作列的处理方法
	 	displayColumns : [0,2,3],		//显示的数据列
	 	notAdd : true,   				//表示无新增、导入按钮
	 	notDel : true,   				//表示无删除按钮
	 	paramFunc : function(){}		//列表params参数生成方法
	 }
 */
CardMgnt.drivers.showList = function(divId,companyId,deptId,options){
	if (!options) options = {}
	CardMgnt.drivers.companyId = companyId;
	CardMgnt.drivers.deptId = deptId;
	
	CardMgnt.drivers.createTable(divId,options)
}
CardMgnt.drivers.createTable = function(divId,opts){
	var columns = []						
	columns[0] = {type:"checkbox"}
	columns[1] = {
		render:function(v,r){
			return "<a href=# onclick=\"CardMgnt.drivers.showDet("+r[CardMgnt.drivers.cols.id]+",true);return false;\">"+v+"</a>";
		}
	}
	var buttons = [];
	if (!opts.isView){
		if (!opts.notAdd){
			buttons.push({value:"增 加",actions:CardMgnt.drivers.add});
			buttons.push({value:"导 入",actions:CardMgnt.drivers.importData});
		}
		if (!opts.notDel)
			buttons.push({value:"删 除",actions:CardMgnt.drivers.remove});
		columns[10] = {
			title:"操作",
			width:"20",
			render:opts.operatRender
		}
	}	
	CardMgnt.drivers.qt = new QueryTable("unit_driver_manage",null,divId,columns,{
		displayColumns : opts.displayColumns,
		columnsConf : false,
		paramFunc:opts.paramFunc?opts.paramFunc : function(){
			return {
				orgUserId:CardMgnt.drivers.companyId,
				deptId:CardMgnt.drivers.deptId,
				status:opts.status
			}
		},
		buttons:buttons
	});
	
	CardMgnt.drivers.qt.showTable();
}
CardMgnt.drivers.showDet = function(id,view){
	var options = {}
	options.companyUserId = CardMgnt.drivers.companyId;
	options.cardUserId = id;
	options.isView = view;
	var url = spellUrl("/client/add_driver.html",options);
	openDialogFrame(url,"查看司机信息",600,800,view?function(){}:CardMgnt.drivers.refresh);
	/**	
	CardMgnt.openDlg("/client/add_driver.html","查看司机信息",600,800,view?function(){}:CardMgnt.drivers.refresh,{
		companyUserId:CardMgnt.drivers.companyId,
		cardUserId:id,
		isView:view
	})
	*/
}
CardMgnt.drivers.add = function(){
	var options = {}
	options.companyUserId = CardMgnt.drivers.companyId;
	options.deptId = CardMgnt.drivers.deptId;
	var url = spellUrl("/client/add_driver.html",options);
	openDialogFrame(url,"新增司机",600,800,CardMgnt.drivers.refresh);
/**	
	CardMgnt.openDlg("/client/add_driver.html","新增司机",660,800,CardMgnt.drivers.refresh,{
		companyUserId:CardMgnt.drivers.companyId,
		deptId:CardMgnt.drivers.deptId
	})
*/
}
CardMgnt.drivers.importData = function(){
	var options = {}
	options.headFile = "drivers";
	var url = spellUrl("/common/import_data.html",options);
	openDialogFrame(url,"导入司机",600,800,CardMgnt.drivers.refresh);
}
CardMgnt.drivers.refresh = function(){
	if (CardMgnt.drivers.qt)
		CardMgnt.drivers.qt.showTable();
}
CardMgnt.drivers.remove = function(){
	var list = CardMgnt.drivers.qt.getBoxValue(true)
	if (list.length < 1){showWarning("请选择需要删除的司机！");return;}
	var ids = []
	for (var i=0;i<list.length;i++){
		var l = list[i];
		ids.push(l[CardMgnt.drivers.cols.id])
		var status = l[CardMgnt.drivers.cols.status];
		if (status != CardUserStatus.UNACTIVATED){
			showError("只能删除未激活状态的司机帐户！");return;
		}
	}
	if (!showQuestion("是否删除这些司机帐户？")) return;
	
	DWR.call("customerService.deleteCardUsers",ids,function(){
		showInformation("司机帐户删除成功！");
		CardMgnt.drivers.refresh();
	},{blockScreen:true})
}

//单位部门
CardMgnt.dept = {
	formName : "deptform"
}
CardMgnt.dept.showData = function(divId,data,options){
	if (!options) options = {}
	var formName = CardMgnt.dept.formName;
	Rpc.loadPage(divId,"/card/dept_all_div.html");
	if (options.isView) $("dept_all_div_btn").style.display = "none";
	Common.initMultiSelect("deptStationLimitTD","定点油站",formName,"stationLimitSel","/card/sel_station_limit.html",500,10);
	var companyUser = data.cardUser;
	CardMgnt.dept.companyUserId = companyUser.id;
	var customer = data.companyCustomer;
	//生成树的必须方法
	window._startLoadXmlTree = function(sSrc, jsNode, newNode) {
		DWR.call("customerService.findDepts", CardMgnt.dept.companyUserId,sSrc, function(result) {
			_xmlFileLoaded(result, jsNode);
		});
	}
	//
	window._createNode = function(dept) {
		if (dept.id) {
			node = createTreeNode(false, dept.deptName, dept.id, "javascript:showProperty()");
		} else
			node = createTreeNode(false, "新部门", null, "javascript:showProperty()");
		node.obj = dept;
		return node;
	}
	window.showProperty = function(){
		CardMgnt.dept.showDept(window.tree.getSelected());
	}
	var obj = {name:customer.name,isRoot:true}
	webTreeHandler.init();
	window.tree = new LoadTree(obj.name, null, "javascript:showProperty()", null, "../images/tree/root.png", "../images/tree/root.png");
	window.tree.obj = obj;
	$("depttree").innerHTML = window.tree;
	window.tree.select();
}
CardMgnt.dept.showDept = function(node){
	if (!node || node.obj.isRoot){
		$("dept_info_div").style.display = "none";
	}else{
		$("dept_info_div").style.display = "";
		var formName = CardMgnt.dept.formName;
		CardMgnt.dept.cancel()
		var dept = node.obj;
		Common.setValues(formName,dept);
		CardMgnt.setStationLimitCtrl($(formName).stationLimitSel,dept.stationLimit);
	}
}
CardMgnt.dept.save = function(){
	var formName = CardMgnt.dept.formName;
	if (!checkForm(formName)) return;
	var dept = Common.getValues(formName);
	var form = $(formName);
	var node = window.tree.getSelected();
	dept.orgUser = CardMgnt.dept.companyUserId;
	if (!node ||!node.parentNode|| node.obj.isRoot){
		showError("请选择上级单位或者部门，再保存部门信息！")
		return;
	}
	dept.parent = node.parentNode.obj.id
	dept.stationLimit = CardMgnt.formatStationLimit(form.stationLimitSel);
	DWR.call("customerService.saveUserDept",dept,function(r){
		showInformation("部门保存成功！")
		if (node) {
			node.obj = r;
			node.setText(r.deptName);
			node.src = r.id;
			node.obj.id = r.id;
			Common.setValues(formName,r);
		}
	},{blockScreen:true});
}
CardMgnt.dept.add = function(){
	var parentNode = window.tree;
	if (window.tree.getSelected()) {
		parentNode = window.tree.getSelected();
	}
	if (parentNode.obj.isRoot || parentNode.obj.id)
		newNodeToTree(parentNode,{childAddText:"请选择单位或者部门，再为其添加下属部门"});
	else
		showError("部门【"+parentNode.text+"】尚未保存！")
}
CardMgnt.dept.remove = function(){
	var node = window.tree.getSelected();
	if (!node) {
		showInformation("请选择需要删除的部门");
		return;
	}
	var sel = function(){
		node.remove();
		window.showProperty();
	}
	if (node.obj.id) {
		if (showQuestion("是否删除部门【"+node.text+"】？")) {
			DWR.call("ejbQueryService.del", "UserDept", node.obj.id, function() {
				showInformation("部门【"+node.text+"】删除成功");
				sel();
			});
		}
	} else {
		sel();
	}
}
CardMgnt.dept.cancel = function(){
	var form = $(CardMgnt.dept.formName);
	form.reset();
	clearErrorView(form);
	var select = form.stationLimitSel;
	while(select.childNodes.length>0){
		var c = select.childNodes[0]
		select.removeChild(c)
	}
}
/**
 * 限站格式化
 */
CardMgnt.formatStationLimit = function(select){
	return CardMgnt._formatLimit(select)
}
/**
 * 将商品限制信息进行格式化 商品id，分号分隔
 */
CardMgnt.formatMerchandiseLimit = function(select,isLimit){
	var merLimit = CardMgnt._formatLimit(select);
	if (!isLimit){
		merLimit = Constants.MER_FULL
	}
	return merLimit
}
/**
 * 将商品限制信息进行格式化 商品id，分号分隔
 */
CardMgnt._formatLimit = function(select,p){
	if (!select) return null;
	if (!p) p = ";";
	var limits = select.childNodes;
	var str = ""
	for (var i=0;i<limits.length;i++){
		var op = limits[i];
		if (!op.value) continue;
		if (str) str += p;
		str += op.value;
	}
	return str;
}
/**
 * 将油品限制信息进行格式化 16进制字符串
 */
CardMgnt.formatOilLimit = function(select,isLimit){

	var oilLimit = CardMgnt._formatLimit(select);
	if (!isLimit){
		oilLimit = Constants.OIL_FULL
	}
	return oilLimit
/**
	if (!select) return Constants.NOT_OIL;
	var limits = select.childNodes;
	var arrays = [];
	for (var i=0;i<256;i++){
		arrays[i] = 0;
	}
	for (var i=0;i<limits.length;i++){
		var op = limits[i];
		arrays[op.value] = 1;
	}
	var res;
	arrays = arrays.join("");
	if (parseInt(arrays) == 0)
		res = Constants.NOT_OIL;
	else
		res = CardMgnt.binaryToHexStr(arrays);
	return res
	*/
}
CardMgnt.setLimitCtrl = function(form,cardUser){
	if (!form || !cardUser) return;
	var result = {}
	if (cardUser.id){
		result = DWR.syncCall("mgntQueryService.findLimits",cardUser.id);
	}else{
		result = DWR.syncCall("mgntQueryService.findLimitsByCardUser",cardUser); 
	}
	CardMgnt.setValueStationLimit(form.stationLimitSel,result.stationLimit);
	CardMgnt.setValueMerLimit(form.merLimitSel,result.merchandiseLimit);
	CardMgnt.setValueOilLimit(form.oilLimitSel,result.oilLimit);
}
CardMgnt.setValueStationLimit = function(select,limits){
	if (!limits || !select) return;
	for (var i=0;i<limits.length;i++){
		var d = limits[i];
		Common.addOption(select,d.uniqueId,d.name);
	}
}
CardMgnt.setStationLimitCtrl = function(select,limits){
	if (!limits || !select) return;
	var result = DWR.syncCall("mgntQueryService.findStationLimits",limits);
	CardMgnt.setValueStationLimit(select,result)
}
CardMgnt.setValueMerLimit = function(select,limits){
	if (!limits || !select) return;
	
	for (var i=0;i<limits.length;i++){
		var d = limits[i];
		Common.addOption(select,d.catCode,d.catName);
	}
}
CardMgnt.setMerLimitCtrl = function(select,limits){
	if (!limits || !select || limits == Constants.MER_FULL) return;
	var result = DWR.syncCall("mgntQueryService.findGoodsCategorise",limits);
	CardMgnt.setValueMerLimit(select,result);
}


CardMgnt.setValueOilLimit = function(select,limits){
	if (!limits || !select) return;
	for (var i=0;i<limits.length;i++){
		var d = limits[i];
		Common.addOption(select,d.uniqueId,d.name);
	}
}
/**
 * 商品、油品限制信息的显示
 */
CardMgnt.setOilLimitCtrl = function(select,limits){
	if (!limits || !select || limits == Constants.OIL_FULL) return;
	var result = DWR.syncCall("mgntQueryService.findOilLimits",limits);
	CardMgnt.setValueOilLimit(select,result);
}

CardMgnt.showMerLimitText = function(limits){
	if (!limits) return;
	var str = "";
	var result = DWR.syncCall("mgntQueryService.findGoodsCategorise",limits);
	for (var i=0;i<result.length;i++){
		var d = result[i];
		if (str) str += ",";
		str += d.catName;
	}
	return str;
}
CardMgnt.showOilLimitText = function(limits){
	if (!limits) return;
	var str = "";
	var result = DWR.syncCall("mgntQueryService.findOilLimits",limits);
	for (var i=0;i<result.length;i++){
		var d = result[i];
		if (str) str += ",";
		str += d.name;
	}
	return str;
/**
	if (!limits || limits == Constants.NOT_OIL) return "";
	var str = "";
	limits = CardMgnt.hexToBinaryStr(limits)
	for (var i=0;i<256;i++){
		var a = limits.charAt(i);
		if (a == "1"){
			var item = Common.getItem('restrictgoods',i)
			if (str) str += ","
			str += item.text;
		}
	}
	return str;
	**/
}

CardMgnt._loadRestrictGoods = function(){
	var result = DWR.syncCall("goodsService.findRestrictedGoods")
	
	var items = []
	var item
	for (var i=0;i<result.length;i++){
		var r = result[i];
		item = {}
		item.code = r[0];
		item.text = r[1];
		items.push(item);
	}
	return items
}

Common.registerSpecialDict('restrictgoods', CardMgnt._loadRestrictGoods)

CardMgnt._loadMgntAuditTypes = function(){
	var result = DWR.syncCall("auditService.findAuditTypesByCategory",AuditCategory.CARDUSER)
	
	var items = []
	var item
	for (var i=0;i<result.length;i++){
		var r = result[i];
		item = {}
		item.code = r.id;
		item.text = r.name;
		items.push(item);
	}
	return items
}

Common.registerSpecialDict('mgnt_audit_type', CardMgnt._loadMgntAuditTypes)

var binaryMap ={"0000":"0","0001":"1","0010":"2","0011":"3","0100":"4","0101":"5","0110":"6","0111":"7","1000":"8","1001":"9","1010":"A","1011":"B","1100":"C","1101":"D","1110":"E","1111":"F"}
CardMgnt.binaryToHexStr = function(str){
	var res = "";
	for (var i = 0;i<str.length;i=i+4){
		var c = str.substring(i,i+4);
		res += binaryMap[c]
	}
	return res;
}

CardMgnt.hexToBinaryStr = function(hexStr){
	var str = "0123456789ABCDEF";
	hexStr = hexStr.toUpperCase();
	var res = ""
	for (var i=0;i<hexStr.length;i++){
		var c = hexStr.charAt(i);
		res += CardMgnt.toBinaryStr(str.indexOf(c))
	}
	return res;
}
CardMgnt.toBinaryStr = function(num){
	var str = ""
	var d = num % 2;
	str = d+"";
	var e = Math.floor(num/2);
	while (e>0){
		str = e%2 + str;
		e = Math.floor(e/2);
	}
	var len = str.length
	for (var i=0;i<4-len;i++){
		str = "0"+str;
	}
	return str
}

//格式化carduser
CardMgnt.parseCardUser = function(result){
	var cardUser = clone(result.cardUser)
	var name,idno,idnoType;
	if (cardUser.type == CardUserType.COMPANY){
		if (result.companyCustomer){
			name = result.companyCustomer.name;
			idno = result.companyCustomer.idno;
			idnoType = result.companyCustomer.idnoType;
		}
	}else if (cardUser.type == CardUserType.NAME || cardUser.type == CardUserType.DRIVER){
		cardUser.deptName = result.dept?result.dept.deptName:''
		var customer = result.customer
		if (customer){
			name = customer.name;
			idno = customer.idno;
			idnoType = customer.idnoType;
		}
		if (result.companyCustomer){
			cardUser.companyName = result.companyCustomer.name;
			cardUser.companyIdno = result.companyCustomer.idno;
		}
	}
	cardUser.name = name;
	cardUser.idno = idno;
	cardUser.idnoType = idnoType;
	cardUser.idnoTypeText = Common.getText("idno_type",idnoType);
	cardUser.statusText = Common.getText(CardUserStatus.CATEGORY,cardUser.status);
	if (result.buildFileStation){			//开户地点
		cardUser.buildFileStationName = result.buildFileStation.name
	}
	if (result.carModel){			//车辆型号
		cardUser.carModelName = result.carModel.name
	}
	if (result.userCardType){
		cardUser.cardTypeName = result.userCardType.name
		cardUser.cardType = result.userCardType.id
	}
	cardUser.currentLevelText = Common.getText("customer_level",cardUser.currentLevel);
	return cardUser
}


CardMgnt.customer = {
	formName : "templetCustomerForm"
}
/**
 * 显示客户档案
 */
CardMgnt.customer.show = function(divId,id,viewType,options){
	if (!options) options = {}
	
	CardMgnt.customer.isCompany = options.isCompany
	
	var customer = {};
	if (id){
		if (CardMgnt.customer.isCompany)
			customer = DWR.syncCall("customerService.getCompanyCustomer",id);
		else
			customer = DWR.syncCall("customerService.getCustomer",id);
	}
	CardMgnt.customer.showCustomer(divId,customer,viewType,options);
}
/**
 * 显示客户档案
 * options = {
 * 		isCompany : true , //是否是单位客户
 * 		isCreate : true		//是否是新建客户信息
 *
 * }
 */
CardMgnt.customer.showCustomer = function(divId,customer,viewType,options){
	if (!options) options = {}
	if (!customer) customer = {};
	
	var formName = CardMgnt.customer.formName;
	var url;
	var isCompany = false;
	if (viewType == CardMgnt.PERSONALALL){
		url = "/card/personal_customer_div.html";
	}else if (viewType == CardMgnt.COMPANYALL){
		url = "/card/company_customer_div.html";
		isCompany = true;
	}
	Rpc.loadPage(divId,url);
	
	var customerForm = $(formName)
	Common.initDict(customerForm.gender,"gender");
	Common.initDict(customerForm.education,"degree","请选择");
	Common.initDict(customerForm.bank,"bank","请选择");
	Common.initDict(customerForm.nativePlace,"province","请选择");
	Common.initDict(customerForm.area,"province","请选择");
	Common.initDict(customerForm.idnoType,"idno_type","请选择");
	Common.initDict(customerForm.industry,"industry","请选择");
	Common.initDict(customerForm.position,"position","请选择");

	if (options.showAll){
		var alink = $(formName+"_a");
		if (alink){
			CardMgnt.showOrHideArea("templetCustomerTable2",alink);
			alink.style.display = "none";
		}
	}
	
	if (options.isCreate){
		var alink = $(formName+"_findByIdno");
		if (alink){
			alink.onclick=function(){
				var idno = customerForm.idno.value;
				var idnoType = customerForm.idnoType.value;
				if (!idno || !idnoType) {showWarning("证件类型和证件号不能为空！");return};
				var c
				if (options.isCompany || isCompany){
					c = DWR.syncCall("customerService.getCompanyCustomerForCardUser",idno,idnoType);
				}else{
					c = DWR.syncCall("customerService.getCustomerForCardUser",idno,idnoType);
				}
				if (!c)
					c = {}
				c.checkIdno = true;
				if (c.id){
					CardMgnt.customer.setValues(formName,c);
					CardMgnt.showViewForm(formName);
					if (!showQuestion("档案已经存在，是否在该档案下继续创建客户资料？")){
						if (typeof window.onCancel == "function"){
							onCancel();
						}
					}
				}else
					showInformation("不存在证件号为"+idno+"的档案！")
			}
			alink.style.display = "";
		}
	}
	if (customer.id){
		customerForm.idnoType.disabled = true;
		customerForm.idnoType.className = "disabled";
		customerForm.idno.readOnly = true;
		customerForm.idno.className = "readonly";
	}

	CardMgnt.customer.setValues(formName,customer);
	if (options.isView)
		CardMgnt.showViewForm(formName);
}

CardMgnt.customer.setValues = function(formName,customer){
	if (!customer.employeeCount) customer.employeeCount = ""
	Common.setValues(formName,customer);
}
CardMgnt.customer.get = function(){
	return Common.getValues(CardMgnt.customer.formName);
}


CardMgnt.customer.save = function(){
	var formName = CardMgnt.customer.formName
	if (!checkForm(formName)) return;
	var customer = CardMgnt.customer.get();
	if (CardMgnt.customer.isCompany){
		DWR.call("customerService.saveCompanyCustomer",customer,function(v){
			showInformation("档案保存成功！");
			if (CardMgnt.customer.saveHandle)CardMgnt.customer.saveHandle(v)
		},{blockScreen:true});
		
	}else
		DWR.call("customerService.saveCustomer", customer,function(v) {
			showInformation("档案保存成功！");
			if (CardMgnt.customer.saveHandle)CardMgnt.customer.saveHandle(v)
		},{blockScreen:true});
}
/**
 * 显示客户信息
 */
CardMgnt.userDetail = {
	divId : null,
	type : CardUserType.NAME,
	options : null,
	data : null
}

CardMgnt.userDetail.show = function(divId,id,type,options){
	if ((!id && !type) || !divId) return;
	if (!options) options = {}
	this.divId = divId;
	this.options = options;
	
	if (id)
		DWR.call("mgntQueryService.getUserInfo",id,function(data){
			var cardUser = data.cardUser;
			CardMgnt.userDetail.data = data;
			CardMgnt.userDetail.showView(divId,cardUser.type,options);
		})
	else if (type)
		CardMgnt.userDetail.showView(divId,type,options);
}
CardMgnt.userDetail.showView = function(divId,type,options){
	this.type = type;
	var tabs = {											//不同的tab触发的方法
		"customer":{name:"tab_customer",text:"档案信息",tabFunc:this.showCustomer},
		"carduser":{name:"tab_carduser",text:"帐号信息",tabFunc:this.showCardUser},
		"dept":{name:"tab_dept",text:"部门信息",tabFunc:this.showDept},
		"drivers":{name:"tab_drivers",text:"司机信息",tabFunc:this.showDrivers}
	}
	var tablist = [];
	var title = "";
	if (type == CardUserType.NAME){
		title = "个人帐户信息";
		tablist.push(tabs["customer"]);
		tablist.push(tabs["carduser"]);
	}else if (type == CardUserType.DRIVER){
		title = "司机单位信息";
		if (this.data && this.data.customer)
			tablist.push(tabs["customer"]);
		tablist.push(tabs["carduser"]);
	}else if (type == CardUserType.COMPANY){
		title = "单位帐户信息";
		tablist.push(tabs["customer"]);
		tablist.push(tabs["carduser"]);
		tablist.push(tabs["dept"]);
		tablist.push(tabs["drivers"]);
	}
	var html = "";
	html += '<div id="'+divId+'_detview" class="form">'
	html += '<div class="formTitle">'+title+'</div>';
	html += '<table cellSpacing="0" cellPadding="4" width="100%" border="0" class="viewTable col3"><tr>';
	html += '<td width="50%"><label>名&nbsp;&nbsp;&nbsp;&nbsp;称</label> <span id="name"></span></td>';
	html += '<td><label>证件类型</label> <span id="idnoTypeText"></span></td>'
	html += '<td><label>证&nbsp;件&nbsp;号</label> <span id="idno"></span></td>'
	html += '</tr><tr>'
	html += '<td width="50%"><label>客户编号</label> <span id="uniqueId"></span></td>'
	html += '<td><label>开户机构</label> <span id="buildFileStationName"></span></td>'
	html += '<td><label>状&nbsp;&nbsp;&nbsp;&nbsp;态</label> <span id="statusText"></span></td>'
	html += '</tr></table>'
	html += '</div>'
	html += '<div class="width97">'
	html += '<div id="'+divId+'_tabsdiv" align="left"></div>'
	html += '<div id="'+divId+'_customerdiv"><div id="'+divId+'_customer_det" class="form"></div><p>'
	if (!this.options.isView){
		html += '<button onclick="CardMgnt.customer.save()">保存档案</button>'
	}
	html += '<button onclick="CardMgnt.userDetail.backList()">返 回</button></p></div>'
	html += '<div id="'+divId+'_carduserdiv" style="display:none;"><div id="'+divId+'_carduser_det" class="form"></div><p>'
	if (!this.options.isView){
		html += '<button onclick="CardMgnt.cardUser.save()">保存帐户</button>'
	}
	html += '<button onclick="CardMgnt.userDetail.backList()">返 回</button></p></div>'
	html += '</div>'
	html += '<div id="'+divId+'_deptsdiv" class="w97border" style="display:none;">'
	html += '<div id="'+divId+'_depts_det"></div>'
	html += '<p><button onclick="CardMgnt.userDetail.backList()">返 回</button></p>'
	html += '</div>'
	html += '<div id="'+divId+'_driversdiv" style="margin-top:-10px;display:none;">'
	html += '<div id="'+divId+'_drivers_det"></div><p><button onclick="CardMgnt.userDetail.backList()">返 回</button></p>'
	html += '</div>'
	$(divId).innerHTML = html;
	Eui.buildTabs(divId + "_tabsdiv",tablist);
	tablist[0].tabFunc();
	if (this.data){
		if (this.type == CardUserType.DRIVER){
			var d = {}
			d.cardUser = this.data.orgUser
			d.customer = this.data.companyCustomer
			d.buildFileStation = this.data.buildFileStation
			Common.showDetail(divId+"_detview",CardMgnt.parseCardUser(d));
		}else
			Common.showDetail(divId+"_detview",CardMgnt.parseCardUser(this.data));
	}
}
CardMgnt.userDetail.showCustomer = function(){
	var det = CardMgnt.userDetail;
	var isCompany = det.type == CardUserType.COMPANY;
	var pageType = isCompany ? CardMgnt.COMPANYALL : CardMgnt.PERSONALALL;
	var customer = isCompany && det.data ? det.data.companyCustomer : det.data.customer;
	CardMgnt.customer.isCompany = isCompany;
	CardMgnt.customer.showCustomer(det.divId + "_customer_det",customer,pageType,{showAll:true});
	
	if (det.options.isView)
		CardMgnt.showViewForm(CardMgnt.customer.formName);
	else
		CardMgnt.customer.saveHandle = function(c){
			if (isCompany)
				det.data.companyCustomer = c
			else
				det.data.customer = c
		}
	det.switchPage(det.divId + "_customerdiv");
}
//显示帐户信息
CardMgnt.userDetail.showCardUser = function(){
	var det = CardMgnt.userDetail;
	var isCompany = det.type == CardUserType.COMPANY;
	CardMgnt.cardUser.showData(det.divId + "_carduser_det",det.data,det.type == CardUserType.COMPANY?CardMgnt.COMPANYALL:CardMgnt.PERSONALALL);
	
	if (det.options.isView)
		CardMgnt.showViewForm(CardMgnt.cardUser.formName);
	else
		CardMgnt.cardUser.saveHandle = function(cardUser){
			det.data.cardUser = cardUser
		}
	det.switchPage(det.divId + "_carduserdiv");
}
CardMgnt.userDetail.showDept = function(){
	var det = CardMgnt.userDetail;
	det.switchPage(det.divId + "_deptsdiv");
	CardMgnt.dept.showData(det.divId + "_depts_det",det.data,det.options);
	if (det.options.isView)
		CardMgnt.showViewForm(CardMgnt.dept.formName);
}
CardMgnt.userDetail.showDrivers = function(){
	var det = CardMgnt.userDetail;
	det.switchPage(det.divId + "_driversdiv");
	var options = {}
	options.notAdd = true;
	options.isView = det.options.isView
	options.operatRender = function(v,r){
		var status = r[9];
		var str = "";
		if (status == CardUserStatus.UNACTIVATED || status == CardUserStatus.OK){
			str += "<a href=# onclick=\"CardMgnt.drivers.showDet("+r[0]+");return false;\">编辑</a>";
		}else
			str += "--";
		return str;
	}
	CardMgnt.drivers.showList(det.divId + "_drivers_det",det.data.cardUser.id,null,options)
}
CardMgnt.userDetail.backList = function(){
	//返回列表
	switchPage("listview");
}
CardMgnt.userDetail.switchPage = function(pageId){
	var pages = [
		this.divId+'_customerdiv',
		this.divId+'_carduserdiv',
		this.divId+'_deptsdiv',
		this.divId+'_driversdiv'
	]
	for (var i=0;i<pages.length;i++){
		var c = $(pages[i]);
		if (!c) continue;
		if (c.id == pageId){
			c.style.display = "";
		}else{
			c.style.display = "none";
		}
	}
}
/**
 * 隐藏或者显示区域
 */
CardMgnt.showOrHideArea = function(targetId,aObj){
	var area = $(targetId);
	if (!area || !aObj) return;
	if (area.style.display == "none"){
		area.style.display = ""
		aObj.innerHTML = "隐藏..."
	}else{
		area.style.display = "none"
		aObj.innerHTML = "更多..."
	}
}
/**
 * 
 */
CardMgnt.checkLimitCtrl = function(select,b){
	if (!select) return;
	select.disabled = !b
	var btns = select.parentNode.parentNode.getElementsByTagName("BUTTON");
	for (var i=0;i<btns.length;i++){
		var btn = btns[i];
		btn.disabled = !b
	}
}

CardMgnt.showViewForm = function(formName){
	var form = $(formName);
	if (!form) return;
	var len = form.elements.length;
	for(var i = 0 ;i< len; i++){
		var ele = form.elements[i];
		if (ele.tagName == "BUTTON"){
			ele.style.display = "none";
		}else if ((ele.tagName == "INPUT" && ele.type == "text") || ele.tagName == "TEXTAREA"){
			ele.readOnly = true;
			ele.className = "readonly";
		}else if ((ele.tagName == "INPUT" && (ele.type == "radio"||ele.type == "checkbox"))){
			ele.disabled = true;
		}else if (ele.tagName == "SELECT"){
			ele.disabled = true;
			ele.className = "disabled";
		}
	}
	var aobjs = form.getElementsByTagName("A");
	for (var i = 0;i<aobjs.length;i++){
		var a = aobjs[i];
		a.style.display = "none";
	}
}
CardMgnt.activForm = function(formName){
	var form = $(formName);
	if (!form) return;
	var len = form.elements.length;
	for(var i = 0 ;i< len; i++){
		var ele = form.elements[i];
		if (ele.tagName == "BUTTON"){
			ele.style.display = "";
		}else if ((ele.tagName == "INPUT" && ele.type == "text") || ele.tagName == "TEXTAREA"){
			ele.readOnly = false;
			ele.className = "";
		}else if ((ele.tagName == "INPUT" && (ele.type == "radio"||ele.type == "checkbox"))){
			ele.disabled = false;
		}else if (ele.tagName == "SELECT"){
			ele.disabled = false;
			ele.className = "";
		}
	}
	var aobjs = form.getElementsByTagName("A");
	for (var i = 0;i<aobjs.length;i++){
		var a = aobjs[i];
		a.style.display = "";
	}
}
CardMgnt.badCard = {}
CardMgnt.badCard.PERSONAL = "card/issue_personal_card.html";
CardMgnt.badCard.DRIVER = "../card/issue_org_card.html";
CardMgnt.badCard.CHANGECARD = "card/change_card.html"
CardMgnt.badCard.RENEW = "card/renew.html"
CardMgnt.badCard.UPGRAD = "card/anon_card_upgrad.html"
//跳转至换卡页面
CardMgnt.badCard.gotoPage = function(asn,badCardType){
	var url = spellUrl("../card/change_issue_badcard.html",{asn:asn,badCardType:badCardType})
	document.location.href = url;
}

//圈提卡内金额、积分
CardMgnt.cardUnload = function(asn,amount,pointAmount,pin){
	var list = []
	if (amount > 0){
		cardUnload(asn,amount,AccountType.FUND,null,pin);
	}else
		list.push(AccountType.FUND)
	if (pointAmount >0){
		var serverTime = DWR.syncCall("cardMgntService.getServerTime");
		cardUnload(asn,pointAmount,AccountType.POINT,serverTime,pin);
	}else
		list.push(AccountType.POINT)
	if (list.length>0)
		DWR.syncCall("cardTxService.revocateCardConsistent",asn,list);
	showInformation("圈提成功!");
}
CardMgnt.showPrintView = function(divId,queryName,logId,title){
	var url = "/card/printview_div.html";
	Rpc.loadPage(divId,url);
	$("printview_title").innerHTML = title;
	Eui.getBillHtml("billview",{
		queryName:queryName,
		logId:logId
	});
}
CardMgnt.billTypeMap = {
	"110001" : {queryName:"kill_with_card_bill",title:"有卡注销凭证"},			//个人有卡销户
	"110002" : {queryName:"kill_without_card_bill",title:"无卡销户凭证"},		//个人无卡销户
	"110003" : {queryName:"revocat_org_card_bill",title:"单位卡销卡凭证"},		//司机有卡销户
	"110004" : {queryName:"revocat_org_bill",title:"单位卡销卡凭证"},			//司机无卡销户
	"110008" : {queryName:"kill_unit_bill",title:"单位销户凭证"},				//单位销户
	"110009" : {queryName:{
			"anonymous":"issue_anon_card_bill",
			"personal":"issue_personal_card_bill",
			"driver":"issue_org_card_bill",
			"psam":"issue_psam_bill",
			"operator":"issue_operator_bill"
		},title:"售卡凭证"},													//售卡
	"120003" : {queryName:"lockCard_bill",title:"挂失凭证"},					//挂失
	"120006" : {queryName:"unLockCard_bill",title:"解挂凭证"},				//处理解挂
	"120008" : {queryName:"abate_bill",title:"延长有效期凭证"},				//处理失效卡
	"120009" : {queryName:"anon_update_bill",title:"不记名卡升级凭证"},		//升级不记名卡
	"120010" : {queryName:"renewCard_bill",title:"补卡凭证"},					//补卡
	"120011" : {queryName:"fit_update_bill",title:"副卡升级凭证"},				//副卡升级
	"120012" : {queryName:"ungray_bill",title:"解灰凭证"},					//解灰
	"120013" : {queryName:"password_bill",title:"密码修改凭证"},				//密码修改
	"120014" : {queryName:"reset_pswd_bill",title:"重置密码凭证"},				//密码重置
	"120020" : {queryName:"blockCard_bill",title:"换卡凭证"},					//换卡
	"120023" : {queryName:"pswd_app_bill",title:"密码启用停用凭证"},			//启用卡密码
	"120024" : {queryName:"pswd_app_bill",title:"密码启用停用凭证"},			//停用卡密码
	"120025" : {queryName:"bad_anoncard_reg_bill",title:"不记名卡售卡损坏登记"},//不记名卡损坏登记
	"120026" : {queryName:"change_issue_badcard_bill",title:"售卡损坏凭证"},	//售卡换卡
	"120027" : {queryName:"customize_draw_personal_bill",title:"个人定制卡领用凭证"},	//个人定制卡片领用
	"120028" : {queryName:"customize_draw_company_bill",title:"单位定制卡片领用凭证"},	//单位定制卡片领用
	//"120029" : {queryName:"customize_draw_company_bill",title:"单位定制卡片领用凭证"},	//定制卡片损坏
	"120022" : {queryName:{
			"personal":"customize_personal_bill",
			"driver":"customize_company_bill"
		},title:"定制卡片凭证"}												//定制卡片
}
CardMgnt.drawPrintView = function(divId,logType,logId,billType){
	var bt = CardMgnt.billTypeMap[logType];
	if (!bt) return;
	var queryName = bt.queryName;
	if (typeof queryName == "object"){
		queryName = queryName[billType]
	}
	CardMgnt.showPrintView(divId,queryName,logId,bt.title)
}
CardMgnt.startCardPin = function(asn){
	while(true){
		try{
			CardMgnt.usePinApp(asn,true)
			break;
		}catch(e){
			if (e.type == "repeat"){
				if (showQuestion("两次密码不一致，是否重新输入！")){
					continue;
				}else{
					showWarning("设置密码失败，卡片采用默认密码！");
				}
			}else
				showError(e.description);
			return;
		}
	}
}
//重置form，由于运营部分form中包含商品限制、油品限制以及校验提示，form重置时需要处理这些
CardMgnt.resetForm = function(form){
	if (typeof form == "string")
		form = $(form);
	if (!form) return;
	form.reset();
	clearErrorView(form);
	CardMgnt.clearLimitSelect(form.stationLimitSel,true);
	CardMgnt.clearLimitSelect(form.merLimitSel);
	CardMgnt.clearLimitSelect(form.oilLimitSel);
}
//清除商品限制、油品限制中的数据
CardMgnt.clearLimitSelect = function(select,p){
	if (!select) return;
	CardMgnt.checkLimitCtrl(select,p);
	while(select.childNodes.length>0){
		var c = select.childNodes[0]
		select.removeChild(c)
	}
}

//显示数据不一致的标志
CardMgnt.showCheckImg = function(ele){
	if(ele){
		var span = document.createElement("SPAN");
		span.innerHTML = "<img id=errorImg name=errorImg src='"+CHECK_ICON+"' align='absmiddle' title='卡内与后台数据不统一'>";
		ele.parentNode.appendChild(span);
	}
}

//判断单位客户是否是本地客户
CardMgnt.checkCompanyLocation = function(cardUser){
	if(!cardUser) {
		showWarning("客户帐户为空");
		return false;
	}
	if (cardUser.type != CardUserType.COMPANY){
		showWarning("不是单位客户帐户！");
		return false;
	}
	var cOrg = Common.cOrg();
	if (cOrg.orgLevel == Constants.ORG_LEVEL_STATION){
		cOrg = {id:cOrg.parent}
	}
	if (cardUser.location != cOrg.id){
		showWarning("不是本地单位客户帐户，不能执行此操作！");
		return false
	}
	return true;
}

//校验售卡卡片是否合法
CardMgnt.checkIssue = function(card,subCardType,cardType){
	try{
		CardMgnt.throwIssueErr(card,subCardType,cardType)
		return true;
	}catch(e){
		showError(e.description);
		return false;
	}
}
//校验售卡卡片是否合法
CardMgnt.throwIssueErr = function(card,subCardType,cardType){
	if (cardType == Constants.ANONYMOUS){
		if (card.baseCardType != BaseCardType.PERSONAL || !subCardType.anonymous){
			throw new Error("该卡不是不记名卡！");
		}
	}else if (cardType == Constants.COMPANY){
		if (card.baseCardType != BaseCardType.COMPANY){
			throw new Error("该卡不是单位卡！");
		}
	}else if (cardType == Constants.PERSONAL){
		if (card.baseCardType != BaseCardType.PERSONAL || subCardType.anonymous){
			throw new Error("该卡不是个人记名卡！");
		}
	}else if (cardType == Constants.OPERATOR){
		if (card.baseCardType != BaseCardType.OPERATOR){
			throw new Error("该卡不是操作员卡！");
		}
	}else if (cardType == Constants.PSAM){
		if (card.baseCardType != BaseCardType.PSAM){
			throw new Error("该卡不是PSAM卡！");
		}
	}else
		throw new Error("错误的业务类型")
	if (card.storeStatus != CardStoreStatus.STORE){
		throw new Error("卡片库存处于"+Common.getText(CardStoreStatus.CATEGORY,card.storeStatus)+"状态,不能出售!");
	}
	if (card.status != CardStatus.INITED){
		throw new Error("卡片处于"+Common.getText(CardStatus.CATEGORY,card.status)+"状态,不能出售!");
	}
	if (card.storeLocation != Common.cOrg().id){
		throw new Error("卡片不属于当前机构！");
	}
	/*
	if (card.baseCardType == BaseCardType.OPERATOR || card.baseCardType == BaseCardType.PSAM){
		if (card.shop){
			throw new Error("该卡已经绑定了商户，不能出售！");
		}
	}
	*/
}
//校验售卡卡片是否合法
CardMgnt.checkRevocate = function(card,subCardType,cardType){
	try{
		CardMgnt.throwRevocatErr(card,subCardType,cardType)
		return true;
	}catch(e){
		showError(e.description);
		return false;
	}
}

//校验售卡卡片是否合法
CardMgnt.throwRevocatErr = function(card,subCardType,cardType){
	if (cardType == Constants.COMPANY){
		if (card.baseCardType != BaseCardType.COMPANY){
			throw new Error("该卡不是单位卡！");
		}
	}else if (cardType == Constants.PERSONAL){
		if (card.baseCardType != BaseCardType.PERSONAL || subCardType.anonymous){
			throw new Error("该卡不是个人记名卡！");
		}
	}else if (cardType == Constants.OPERATOR){
		if (card.baseCardType != BaseCardType.OPERATOR){
			throw new Error("该卡不是操作员卡！");
		}
	}else if (cardType == Constants.PSAM){
		if (card.baseCardType != BaseCardType.PSAM){
			throw new Error("该卡不是PSAM卡！");
		}
	}else
		throw new Error("错误的业务类型");
		
	if (card.storeStatus != CardStoreStatus.IN_USE){
		throw new Error("卡片库存处于"+Common.getText(CardStoreStatus.CATEGORY,card.storeStatus)+"状态,不能注销!");
	}
	if (card.status != CardStatus.OK &&(card.status != CardStatus.BLACK ||(card.blackType != MgntOtherConstant.CARD_BLACKTYPE_OFFICIAL && card.blackType != MgntOtherConstant.CARD_BLACKTYPE_TEMP)) ){
		if (card.status == CardStatus.BLACK)
			throw new Error("卡片处于"+Common.getText("black_type",card.blackType)+"状态,不能注销!");
		else
			throw new Error("卡片处于"+Common.getText(CardStatus.CATEGORY,card.status)+"状态,不能注销!");
	}
	if (card.baseCardType == BaseCardType.OPERATOR || card.baseCardType == BaseCardType.PSAM){
		if (!card.shop){
			throw new Error("该卡没有绑定商户，不能注销！");
		}
	}
}

//校验卡片是不是流通中的正常卡
CardMgnt.checkInUseCard = function(card,baseTypes){
	try{
		CardMgnt.throwInUseCardErr(card,baseTypes)
		return true;
	}catch(e){
		showError(e.description);
		return false;
	}
}
//校验卡片是不是流通中的正常卡,以error形式抛出
CardMgnt.throwInUseCardErr = function(card,baseTypes){
	if (!card)
		throw new Error("卡片不存在！");
	if (!baseTypes){
		baseTypes = [BaseCardType.PERSONAL,BaseCardType.COMPANY]
	}
	var b = false
	for (var i=0;i<baseTypes.length;i++){
		if (card.baseCardType == baseTypes[i]){
			b = true;break;
		}
	}
	if (!b)
		throw new Error("卡片为"+Common.getText(BaseCardType.CATEGORY,card.baseCardType)+"，不能执行此操作！");
	if (card.status != CardStatus.OK){
		throw new Error("卡片为"+Common.getText(CardStatus.CATEGORY,card.status)+"状态，不能执行此操作！");
	}
	if (card.storeStatus != CardStoreStatus.IN_USE){
		throw new Error("卡片为"+Common.getText(CardStoreStatus.CATEGORY,card.storeStatus)+"状态，不能执行此操作!");
	}
	
}
CardMgnt.checkCardAsn = function(asn){
	try{
		getCard();
		CardMgnt.throwCardAsnErr(asn)
		return true;
	}catch(e){
		showError(e.description);
		return false;
	}
}
CardMgnt.throwCardAsnErr = function(asn){
	var tempAsn = getAsn();
	if(tempAsn != asn){	//判断读卡时和圈存时是否为同一张卡片
		throw new Error("卡片有误，请重新读卡");
	}
}
/**
 * 开窗口方法
 * @param url 页面的url
 * @param title 页面的title
 * @param width 窗口的宽度
 * @param height 窗口高度
 * @param handle 窗口关闭时的回调方法
 * @param options 向窗口传递的参数，只能是string、int等简单类型

CardMgnt.openDlg = function(url,title,height,width,handle,options){
	var url = spellUrl(url,options)
	openDialogFrame(url,title,height?height:400,width?width:500,handle);
} */


CardMgnt.convertCardObject = function(data,card){
	var cardObj = clone(data.card);
	var customer = data.customer;
	var company = data.companyCustomer;
	var subCardType = data.cardType;
	var cardUser = data.cardUser;
	var orgUser = data.orgUser;
	var location = data.location;
	
	//卡片数据
	if(card){
		if(card.pin)
			cardObj.pin = card.pin;
		if(card.cardBalance)
			cardObj.cardBalance = Format.fenToYuan(card.cardBalance);
		if(card.cardLoyaltyBalance)
			cardObj.cardLoyaltyBalance = Format.fenToYuan(card.cardLoyaltyBalance);
	}
	cardObj.serverTime = data.serverTime?data.serverTime:"";
	if (customer){
		cardObj.name = customer.name;
		cardObj.idno = customer.idno;
		cardObj.idnoTypeText = Common.getText("idno_type",customer.idnoType);
		cardObj.phone = customer.phone;
		cardObj.zipcode = customer.zipcode;
	}
	if (company){
		cardObj.companyName = company.name;
	}
	cardObj.subCardTypeText = subCardType?subCardType.name:"";
	cardObj.issuerName = data.issueOrg?data.issueOrg.name:'';
	cardObj.issuerUniqueId = data.issueOrg?data.issueOrg.uniqueId:'';
	cardObj.baseCardTypeText = Common.getText("base_card_type",cardObj.baseCardType);
	cardObj.statusText =Common.getText("card_status",cardObj.status);
	cardObj.cardTypeText = Common.getText("base_card_type",cardObj.cardType);			//转换卡类型字典
	cardObj.blackTypeText = Common.getText("black_type",cardObj.blackType);				//转换黑卡类型字典
	cardObj.cardStatusText = Common.getText("card_status",cardObj.cardStatus);			//转化卡状态字典
	if(cardObj.expiredTime)
		cardObj.expiredTime = cardObj.expiredTime.format();						//转换为显示日期格式
	cardObj.spareBalance = Format.fenToYuan(cardObj.spareBalance);							//转换金额单位[分]为[元]
	cardObj.balance = Format.fenToYuan(cardObj.balance);
	cardObj.spareLoyaltyBalance = Format.fenToYuan(cardObj.spareLoyaltyBalance);
	cardObj.loyaltyBalance = Format.fenToYuan(cardObj.loyaltyBalance);
	cardObj.foregift = Format.fenToYuan(data.foregift);
	cardObj.fee = Format.fenToYuan(data.fee);
	cardObj.shopName = data.shop?data.shop.name:'';
	cardObj.shopUnique = data.shop?data.shop.uniqueId:'';
	cardObj.companyUserId = data.companyUserId;											//司机的单位帐户id
	if (cardUser){
		cardObj.uniqueId = cardUser.uniqueId;
		cardObj.usePinText = cardUser.usePin ? "是":"否"
		cardObj.isMasterCardText = cardUser.isMasterCard ? "是":"否"
		cardObj.currentLevelText = Common.getText("customer_level",cardUser.currentLevel);
		cardObj.contractType = cardUser.contractType;
		cardObj.internalText = cardUser.internal ? "是":"否";
		cardObj.timeLimit = cardUser.timeLimit?cardUser.timeLimit:'';
		cardObj.quantityLimit = cardUser.quantityLimit?cardUser.quantityLimit:'';
		cardObj.amountLimit = cardUser.amountLimit?Format.fenToYuan(cardUser.amountLimit):'';
		cardObj.quantityNumber = cardUser.quantityNumber?cardUser.quantityNumber:'';
		cardObj.frequency = cardUser.frequency?cardUser.frequency:'';
		cardObj.carLicense = cardUser.carLicense;
		cardObj.invoiceTypeText = Common.getText(InvoiceType.CATEGORY,cardUser.invoiceType);
		cardObj.oilLimitText = CardMgnt.showOilLimitText(cardUser.oilLimit);
		cardObj.merchandiseLimitText = data.merchandiseLimitText;
		cardObj.stationLimitText = data.stationLimitText
	} 
	if (orgUser){
		cardObj.companyUniqueId = orgUser.uniqueId
	}
	if (location){
		cardObj.locationUniqueId = location.uniqueId
	}
	//后台帐户信息
	if (data.accounts){
		var items = Common.getItems('account_type');
		var balanceName,spareBalanceName,code,tSpareBalance,tBalance;
		for(var i=0;i<items.length;i++){
			code = items[i].code;
			tSpareBalance = data.accounts["user_"+code];
			tBalance = data.accounts["card_"+code];
			balanceName = "";
			spareBalanceName = "";
			//对照code产生属性
			if(code == AccountType.FUND){//资金
				balanceName = "balance";
				spareBalanceName = "spareBalance";
			}
			else if (code == AccountType.POINT){//积分
				balanceName = "loyaltyBalance";
				spareBalanceName = "spareLoyaltyBalance";
			}
			if(tBalance && balanceName != ""){
				cardObj[balanceName] = Format.fenToYuan(tBalance.balance);
			}
			if(tSpareBalance && spareBalanceName != ""){
				cardObj[spareBalanceName] =  Format.fenToYuan(tSpareBalance.balance);
			}
		}
	}
	return cardObj;
}
//form,cardObj 卡片内的数据,cardInfo 后台写卡数据
CardMgnt.contrastCard = function(form,cardInfo){
	if (typeof form != "object") form = $(form);
	var map = {
		petroLimit : "oilLimitText",
		goodLimit : "merchandiseLimitText",
		oneDayTimesLimit : "timeLimit",
		oneDayAmountLimit : "amountLimit",
		oneDayNumLimit : "quantityLimit",
		oneTimesNumLimit : "quantityNumber",
		frequencyLimit : "frequency",
		carNoLimit : "carLicense",
		pinFunction : "usePinText",
		accountCode : "uniqueId",
		invoiceKind : "invoiceTypeText",
		unitCode : "companyUniqueId",
		issuerCity : "locationUniqueId",

		contractKind : "contractType",
		clientCurrentGrade : "currentLevelText",
		bankUserID : "internalText",
		userName : "name",
		userCID : "idno",
		userCKind : "idnoTypeText",
		whiteLimit : "stationLimitText"
		
	}
	getCard();
	var cObj = getApplicationInfo();
	var pObj = getCardPersonInfo();
	var cardObj = CardMgnt.merge(cObj,pObj);
	for (prop in cardObj){
		var c = cardObj[prop];
		if (typeof c == "function") continue;
		if (cardInfo[prop] != c){
			//alert(prop + " 卡内：" + c + " <br>后台： " + cardInfo[prop])
			CardMgnt.showCheckImg(form[map[prop]]);
		}
	}
}
//日常运营部分
//输入卡密码
CardMgnt.inputCardPin = function(msg,needInput){
	if (!msg) msg = "请持卡人输入密码";
	var needPin = false;
	if(needInput == true){
		needPin = true;
	}
	else{
		needPin = getNeedPin();
	}
	if (needPin){
		var pin;
		/** 模拟密码键盘 */
		var isTest = false;
		if (isTest){
			pin = openDialogFrame("/card/input_cardpin.html",msg?msg:"请持卡人输入密码",160,280); 
		}else{
			/** 密码键盘 */
			Loading.blockScreen();
			if(!showQuestion(msg)){
				Loading.cancelBlockScreen();
				throw new Error("取消输入卡密码！")
			}
			getCard();
			pin = getPin();
			if(!Validator.isCardPin(pin)){
				throw new Error("请输入合法的卡密码(6位数字)");
			}
		}
		if (!pin)
			throw new Error("未输入卡密码！");
		return pin;
	}else
		return Constants.DEFPIN;
}
CardMgnt.merge = function(rObj,newObj){
	if (typeof rObj != "object" || typeof newObj != "object") return null;
	
	for (prop in newObj){
		if(newObj.hasOwnProperty(prop)){
			rObj[prop] = newObj[prop]
		}
	}
	return rObj;
}


SimulatePos = {}

SimulatePos.savePosInfo = function(data){
	if (!data) return;
	writeFile("eftNo",data.eftNo);
	writeFile("eftSn",data.eftSn);
}
SimulatePos.putPosInfo = function(data){
	if (!data) return;
	var _put = function(d){
		d.eftSn = parseInt(readFile("eftSn")) + 1;
		d.eftNo = readFile("eftNo");
		if (isNaN(parseInt(d.eftSn)) || isNaN(parseInt(d.eftNo))){
			SimulatePos.clearFile();
			throw new Error("readfileerr");
		}
	}
	try{
		_put(data);
	}catch(e){
		if (e.description == "readfileerr"){
			var eftNo = DWR.syncCall("cardReaderService.getCardReader");
			SimulatePos.savePosInfo({eftNo:eftNo,eftSn:0})
			_put(data);
		}else
			throw e
	}
}
SimulatePos.sendRequest = function(){
	var flag;
	try{
		flag = readFile("flag");
	}catch(e){
		if (e.description == "readfileerr"){
			var eftNo = DWR.syncCall("cardReaderService.getCardReader");
			SimulatePos.savePosInfo({eftNo:eftNo,eftSn:0});
		}else
			throw e
	}
	if (flag != "true") return;
	var verb = readFile("verb");
	var path = readFile("path");
	var query = readFile("query");
	var req;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	}
	else if (window.ActiveXObject && !(navigator.userAgent.indexOf('Mac') >= 0 && navigator.userAgent.indexOf("MSIE") >= 0)) {
		req = DWR._newActiveXObject(DWR._XMLHTTP);
	}
	if (verb=="GET") {
		req.open("GET",path+(query==""?"":'?'+query), false);
		req.setRequestHeader('Content-Type', 'text/plain');
		req.send(null);
	}else{
		req.open("POST", path, false)
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send(query);
	}
	var c = {}
	c.req = req;
	c.completed = false;
	c.simulatePos = true;
	c.async = false;
	DWR._stateChange(c);
	SimulatePos.clearRequest();
}
SimulatePos.saveRequest = function(actionName){
	if (!actionName)
		throw new Error("must provide actionName")
	var args = arguments;
	var c = {}
	var lastArgIndex = args.length -1;
	var ss = actionName.split('.')
	var path = contextRoot + "d/dwr/"+ss[0]
	if (ss[1]) path+="/"+ss[1]
	c.path = path;
	c.verb = DWR._verb;
	c.timeout = DWR._timeout;
	c.async = false;
	c.directreturn = true;
	c.map = {};

	for (var i = 1; i <= lastArgIndex; i++) {
		if (args[i]){
			c.map['p'+(i-1)] = args[i].toJSONString();
		}		
	}
	c.completed = false;
	
	var query = ""
	for (prop in c.map) {
		if (typeof c.map[prop] != "function") {
			query += prop + "=" + encodeURIComponent(c.map[prop]) + "&";
		}
	}
	writeFile("flag","true");
	writeFile("verb",c.verb);
	writeFile("path",c.path);
	writeFile("query",query);
}
SimulatePos.clearRequest = function (){
	writeFile("flag","false");
	writeFile("verb","");
	writeFile("path","");
	writeFile("query","");
}
SimulatePos.clearFile = function(){
	SimulatePos.clearRequest();
	writeFile("eftSn","");
	writeFile("eftNo","");
}
/**
 * 卡充值
 * @param asn 卡号
 * @param amount 充值金额
 */
function cardDeposit(asn,amount,accCode,paymentType,bankTrade,pin){
	var tempAsn;
	try{
		getCard();
		tempAsn = getAsn();
	}catch(e){
		e.type = 'card';
		throw e;
	}
	if(tempAsn != asn){	//判断读卡时和圈存时是否为同一张卡片
		var e = new Error("卡片有误，请重新读卡");
		e.type = 'card';
		throw e;
	}
	
	SimulatePos.sendRequest();
	var keyData = {}
	var result = null;
	if(accCode == AccountType.FUND){
		keyData = init4Load(pin,amount);
		SimulatePos.putPosInfo(keyData);
	}
	else{
		throw new Error("帐户类型错误！");
	}
	if (paymentType == Constants.PAYMENT_CASH){
		result = DWR.syncCall("cardTxService.cashDeposit"
								,asn,amount
								,accCode
								,0
								,keyData
							);
	}else if (paymentType == Constants.PAYMENT_CHEQUE){
		throw new Error("支票不能卡充值");return;
	}else if (paymentType == Constants.PAYMENT_BANK){
		result = DWR.syncCall("cardTxService.bankDeposit"
								,asn
								,amount
								,accCode
								,bankTrade
								,keyData
							);
	}
	
	SimulatePos.savePosInfo(keyData);
	try{
		if(accCode == AccountType.FUND){
			credit4Load(result.serverTime.substring(0,8),result.serverTime.substring(8),result.mac2.toUpperCase());	
		}
		else if(accCode == AccountType.POINT){
			credit4LoyaltyLoad(result)
		}
	}catch(e){
		try{
			//,function(res){},{async:false,simulateSave:SimulatePos.saveRequest,simulateClear:SimulatePos.clearRequest}
			SimulatePos.saveRequest("cardTxService.rollbackLoad",keyData.eftNo,keyData.eftSn)
			DWR.syncCall("cardTxService.rollbackLoad",keyData.eftNo,keyData.eftSn);
			SimulatePos.clearRequest();
		}catch(e){
		}
		throw new Error("写卡失败，请重新操作");
	}
	
	return result
}
//圈存动作
function cardLoad(asn,amount,accCode,spare,pin){
	getCard();
	var tempAsn = getAsn();
	if(tempAsn != asn){	//判断读卡时和圈存时是否为同一张卡片
		throw new Error("卡片有误，请重新读卡");
	}
	
	amount = parseInt(amount)
	spare = parseInt(spare)
	if(amount>spare){
		throw new Error("圈存金额(积分)应小于备用金余额(积分)");
	}
	
	SimulatePos.sendRequest();
	
	if(accCode == AccountType.FUND){	
		return _cardLoad(asn, amount ,accCode,pin)
	}else if(accCode == AccountType.POINT){
		//积分圈存初始化
		var initRes = DWR.syncCall("cardTxService.initLyLoad",asn,accCode,amount)
		return _cardLoad(asn, amount ,accCode,pin,initRes);
	}
}	

function _cardLoad(asn, amount ,accCode,pin,cmdData){
	var keyData = {}
	var balance
	if(accCode == AccountType.FUND){
		keyData = init4Load(pin,amount);
		SimulatePos.putPosInfo(keyData);
	}
	else if(accCode == AccountType.POINT){
		keyData = init4LoyaltyLoad(pin,cmdData.serverTime,cmdData.cmd)
		keyData.cardBalance = keyData.cardLoyaltyBalance;
		SimulatePos.putPosInfo(keyData);
	}
	//圈存
	var trade = DWR.syncCall("cardTxService.load" , asn, amount ,accCode ,keyData);
	SimulatePos.savePosInfo(keyData);
	try{
		if(accCode == AccountType.FUND){
			credit4Load(trade.serverTime.substring(0,8),trade.serverTime.substring(8),trade.mac2.toUpperCase());	
		}
		else if(accCode == AccountType.POINT){
			credit4LoyaltyLoad(trade)
		}
	}catch(e){
		//TODO 冲正
		SimulatePos.saveRequest("cardTxService.rollbackLoad",keyData.eftNo,keyData.eftSn)
		DWR.syncCall("cardTxService.rollbackLoad",keyData.eftNo,keyData.eftSn)
		SimulatePos.clearRequest()
		throw new Error("写卡失败，请重新操作<br>错误原因："+e.description);
	}	
	return trade
}
//圈提和卡片充值撤销
function cardUnload(asn,amount,accCode,serverTime,pin,origId,payType){
	amount = parseInt(amount)
		
	try{
		getCard();
		var tempAsn = getAsn();
	}catch(e){
		e.type = 'card';
		throw e;
	}
	if(tempAsn!=asn){
		var error = new Error("卡片有误，请重新读卡");
		error.type = 'card';
		throw error;
	}
	
	SimulatePos.sendRequest();
	var keyData = {}
	if(accCode == AccountType.FUND){	
		keyData = init4UnLoad(pin,amount)
		SimulatePos.putPosInfo(keyData);
	}else if(accCode == AccountType.POINT){
		keyData = init4LoyaltyUnload(pin,amount,serverTime)
		keyData.cardBalance = keyData.cardLoyaltyBalance;
		SimulatePos.putPosInfo(keyData);
	}
	if(amount>keyData.cardBalance){
		throw new Error("圈提金额应小于等于卡片余额");
	}

	if(origId==null){// 圈提
		var result = DWR.syncCall("cardTxService.unload",asn,amount,accCode,keyData)
		return _confirmUnload(accCode,result,keyData)
	}else{ //充值撤销
		var result = DWR.syncCall("cardTxService.cancelCardDeposit",origId,payType,asn,amount,accCode,keyData)
		return _confirmUnload(accCode,result,keyData)
	}
}
function _confirmUnload(accCode,result,keyData){
	SimulatePos.savePosInfo(keyData);
	try{
		if(accCode == AccountType.FUND){	
			debit4Unload(result.serverTime.substring(0,8),result.serverTime.substring(8),result.mac2.toUpperCase())
		}else if(accCode == AccountType.POINT){
			debit4LoyaltyUnload(result)
		}
	}catch(e){
		SimulatePos.saveRequest("cardTxService.cancelTempTrades",keyData.eftNo,keyData.eftSn)
		DWR.syncCall("cardTxService.cancelTempTrades",keyData.eftNo,keyData.eftSn)
		SimulatePos.clearRequest()
		throw new Error("交易失败，请重新操作<br>错误原因："+e.description)
	}
	
	SimulatePos.saveRequest("cardTxService.confirmUnload",keyData.eftNo,keyData.eftSn)
	var trade = DWR.syncCall("cardTxService.confirmUnload",keyData.eftNo,keyData.eftSn)
	SimulatePos.clearRequest()
	return trade
}

